package com.microframework.base.data.utils;

import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.MediaType;
import java.io.File;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

public class MultipartFormDataBuilder {

    /**
     * 构建支持嵌套结构的 multipart/form-data
     * @param formData JSON 数据（可能包含嵌套对象或数组）
     * @return MultipartBody
     */
    public static MultipartBody buildMultipartFormData(JSONObject formData) {
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        
        if (formData != null) {
            addJsonToMultipart(builder, formData, "");
        }
        
        return builder.build();
    }

    /**
     * 递归添加 JSON 数据到 MultipartBody.Builder
     * @param builder MultipartBody.Builder
     * @param data 当前层级的 JSON 数据
     * @param parentKey 父级 key（用于嵌套结构，如 "user[name]"）
     */
    private static void addJsonToMultipart(MultipartBody.Builder builder, Object data, String parentKey) {
        if (data instanceof JSONObject) {
            // 处理嵌套对象
            JSONObject jsonObject = (JSONObject) data;
            for (String key : jsonObject.keySet()) {
                String currentKey = parentKey.isEmpty() ? key : parentKey + "[" + key + "]";
                addJsonToMultipart(builder, jsonObject.get(key), currentKey);
            }
        } else if (data instanceof JSONArray) {
            // 处理数组
            JSONArray jsonArray = (JSONArray) data;
            for (int i = 0; i < jsonArray.size(); i++) {
                String currentKey = parentKey + "[" + i + "]";
                addJsonToMultipart(builder, jsonArray.get(i), currentKey);
            }
        } else if (data instanceof String) {
            // 普通字符串
            builder.addFormDataPart(parentKey, (String) data);
        } else if (data instanceof byte[]) {
            // 二进制数据（如文件字节流）
            builder.addFormDataPart(
                parentKey,
                null,
                RequestBody.create((byte[]) data, MediaType.parse("application/octet-stream"))
            );
        } else if (data instanceof File) {
            // 文件对象
            File file = (File) data;
            builder.addFormDataPart(
                parentKey,
                file.getName(),
                RequestBody.create(file, MediaType.parse("application/octet-stream"))
            );
        } else if (data != null) {
            // 其他类型（如数字、布尔值）转成字符串
            builder.addFormDataPart(parentKey, data.toString());
        }
    }

    // 使用示例
    public static void main(String[] args) {
        String jsonStr = "{\n" +
                "  \"name\": \"张三\",\n" +
                "  \"age\": 25,\n" +
                "  \"address\": {\n" +
                "    \"city\": \"北京\",\n" +
                "    \"street\": \"朝阳区\"\n" +
                "  },\n" +
                "  \"hobbies\": [\"篮球\", \"音乐\"],\n" +
                "  \"avatar\": \"<FILE_DATA>\"\n" +
                "}";

        JSONObject formData = JSON.parseObject(jsonStr);
        // 假设 avatar 是文件数据（这里简化成 byte[]，实际可能是 File 对象）
        formData.put("avatar", new byte[]{0x01, 0x02, 0x03});

        MultipartBody multipartBody = buildMultipartFormData(formData);
        System.out.println("Multipart 请求体构建完成！");
    }
}
